package com.basic.java.spring5.AOP.jdkactiveproxy.proxy;


import com.basic.java.spring5.AOP.jdkactiveproxy.dao.UserDao;
import com.basic.java.spring5.AOP.jdkactiveproxy.dao.impl.UserDaoImpl;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 使用Proxy类创建接口代理对象
 * 创建时间：2022/3/13 15:23
 *
 * @author gejin
 */
public class JdkProxy {
    public static void main(String[] args) {
        // 创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};

        UserDaoImpl userDao = new UserDaoImpl();
        Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));

        int result = userDao.add(1, 2);
        System.out.println("result: " + result);

    }
}

// 创建代理对象
class UserDaoProxy implements InvocationHandler {
    //1 把创建的是谁的代理对象，把谁传递过来
    //有参数构造传递
    public Object object;

    public UserDaoProxy(Object object) {
        this.object = object;
    }

    // 增强的逻辑
    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        //方法之前
        System.out.println("方法之前执行...." + method.getName() + " :传递的参数..." + Arrays.toString(objects));
        Object res = method.invoke(object, objects);
        //方法之后
        System.out.println("方法之后执行...." + object);

        return res;

    }
}
